﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.adapter.CarListAdapter;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;
/**
 * 我的车辆
 * @author kuanter
 *
 */
public class MyCarActivity extends WuyangBaseActivity {

	protected static final int INIT_NO_CAR = 555;

	private ListView lv_my_car;

	private DataLoader dataLoader;
	private Intent intent = new Intent();
	private int carInfoIndex;
	protected CarListAdapter carListAdapter;
	private List<VehicleInfo> vehicleInfos ;
	/**
	 * 请求车辆信息响应值
	 */
	Handler handler = new Handler() {

		private int flag;

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				// String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				Log.i(TAG, result);
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status

							JSONObject jsonObject = JSON.parseObject(result);
							String vehicleInfoListStr = jsonObject.getString("vehicleInfoList");
							if ("[]".equals(vehicleInfoListStr)) {
								showToast("信息暂无");
								flag = INIT_NO_CAR ;
							} else {
								// 缓存vehicleInfos
								vehicleInfos = JSON.parseArray(
										vehicleInfoListStr, VehicleInfo.class);
								//ObjectCache.set("vehicleInfos", vehicleInfos);
								carListAdapter = new CarListAdapter(vehicleInfos, MyCarActivity.this);
								lv_my_car.setAdapter(carListAdapter);
							}

						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							showToast(StringUtil.geterrorMsg(result));
						}
					} catch (JSONException e) {
						finishProgress();
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("网络连接错误");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				vehicleInfos = null;

				showToast("网络错误!");
				break;
			}
		}
	};
	/**
	 * 更新车辆信息响应
	 */
	Handler handler1 = new Handler() {
		private int flag;
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
//							showToast("更新车辆成功！");
							JSONObject jsonObject = JSON.parseObject(result);
							String vehicleId = jsonObject.getString("vehicleId");
							for(VehicleInfo vehicleInfo:CarListAdapter.vehicleInfos){
								if(vehicleId.equals(vehicleInfo.getId())){
									vehicleInfo.setModification(false);
								}
							}
						} else {
							finishProgress();
							// 显示返回数据中 errorMsg 字段值
//							showToast("更新车辆失败！");
						}
					} catch (JSONException e) {
						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private View my_car_back_btn;
	private View add_car_info_btn;

	private String pp; //车辆品牌

	private String xh; //车牌号

	private TextView car_brand_and_model_tv;

	private ImageView brand_logo_iv;

	private TextView licensePlateNumber_tv;

	private DatePickerDialog datepick;

	private String car_number;

	private String car_annual_audit_deadline;

	private String car_insurance_deadline;
	public static final int CHOOSE_LINCENSE_PLATE_NUMBER = 255;
	public static final int CHOOSE_CAR_BRAND_MODEL = 256;
	private int userId;
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		switch (requestCode) {
		case CHOOSE_LINCENSE_PLATE_NUMBER:
			if (null == data) {
				
			} else {
				// data.getStringArrayExtra("province");
				// data.getStringExtra("car_number");
				int position = data.getIntExtra("position", -1);
				if (position >= 0) {
					/*licensePlateNumber_tv = (TextView) lv_my_car.getChildAt(
							position).findViewById(R.id.licensePlateNumber_tv);
					licensePlateNumber_tv.setText(data
							.getStringExtra("province")
							+ data.getStringExtra("car_number"));*/
					VehicleInfo vehicleInfo1 = new VehicleInfo();
					vehicleInfo1.setId(vehicleInfos.get(position).getId());
					vehicleInfo1.setLicensePlateNumber(data.getStringExtra("province")+ data.getStringExtra("car_number"));
					carListAdapter.updateDataItem(position, vehicleInfo1);
				}
			}
			break;
		case CHOOSE_CAR_BRAND_MODEL:
			if (null == data) {

			} else {
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				int position = data.getIntExtra("position", -1);
				/*if (position >= 0) {
					TextView t = (TextView) (lv_my_car.getChildAt(position)
							.findViewById(R.id.car_brand_and_model_tv));
					t.setText(pp + "  " + xh);
				}

				brand_logo_iv = (ImageView) lv_my_car.getChildAt(position)
						.findViewById(R.id.brand_logo_iv);
				brand_logo_iv.setImageResource(new BrandStrToIconUtil()
						.getBrandIcon(pp));*/
				if(position >= 0){
					VehicleInfo vehicleInfo2 = new VehicleInfo();
					vehicleInfo2.setId(vehicleInfos.get(position).getId());
					vehicleInfo2.setVehicleBrand(pp);
					vehicleInfo2.setVehicleModels(xh);
					carListAdapter.updateDataItem(position, vehicleInfo2);
				}
			}
			break;
		case MainConstants.ADD_VEHICLE:
			if (data != null) {
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				car_number = data.getStringExtra("car_number");
				car_annual_audit_deadline = data
						.getStringExtra("car_annual_audit_deadline");
				car_insurance_deadline = data
						.getStringExtra("car_insurance_deadline");
				String carID = data.getStringExtra("carID");
				VehicleInfo vehicleInfo = new VehicleInfo();
				vehicleInfo.setId(carID);
//				vehicleInfo.setInsuranceCompany("");
				vehicleInfo.setLicensePlateNumber(car_number);
				vehicleInfo.setVehicleBrand(pp);
				vehicleInfo.setVehicleModels(xh);
				vehicleInfo.setInspectionExpireTime(car_annual_audit_deadline);
				vehicleInfo.setInsuranceEndTime(car_insurance_deadline);
				if (null == CarListAdapter.vehicleInfos||CarListAdapter.vehicleInfos.size()==0) {
					List<VehicleInfo> vehicleInfos = new ArrayList<VehicleInfo>();
					vehicleInfos.add(vehicleInfo);
					carListAdapter = new CarListAdapter(vehicleInfos, MyCarActivity.this);
					lv_my_car.setAdapter(carListAdapter);
				} else {
					carListAdapter.addDataItem(vehicleInfo);
				}
			}
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	ProApplication application;

	private VehicleInfo updatedVehicleInfo;
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 获取我的车辆列表信息
				if(null != CarListAdapter.vehicleInfos&&CarListAdapter.vehicleInfos.size()>0){
					List<VehicleInfo> vehicleInfos = CarListAdapter.vehicleInfos;
					carListAdapter = new CarListAdapter(vehicleInfos, MyCarActivity.this);
					lv_my_car.setAdapter(carListAdapter);
				}else{
					dataLoader = new DataLoader(this);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
					String userId = sp.getString("id", "");
					params.add(new BasicNameValuePair("vehicleInfo.userId", userId));
					dataLoader.DisplayData(
							MainConstants.HOST_test + HttpConfigAPI.FINDVEHICLE, params,
							handler, "", false);
					showProgress("正在加载数据...");
				}
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		application = (ProApplication) getApplication();
		setContentView(R.layout.my_car);
		this.initBodyControlView();
		this.registerListener();
		lv_my_car = (ListView) findViewById(R.id.lv_my_car);
		Log.i("aaa", lv_my_car + "----on");
		lv_my_car.setDivider(null);
		
		userId = SharePrefenceUtil.getUserID(this);
		// 获取我的车辆列表信息
		if(null != CarListAdapter.vehicleInfos&&CarListAdapter.vehicleInfos.size()>0){
			vehicleInfos = CarListAdapter.vehicleInfos;
//			List<VehicleInfo> vehicleInfos = CarListAdapter.vehicleInfos;
			carListAdapter = new CarListAdapter(vehicleInfos, MyCarActivity.this);
			lv_my_car.setAdapter(carListAdapter);
		}else{
			dataLoader = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
			String userId = sp.getString("id", "");
			params.add(new BasicNameValuePair("vehicleInfo.userId", userId));
			dataLoader.DisplayData(
					MainConstants.HOST_test + HttpConfigAPI.FINDVEHICLE, params,
					handler, "", false);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.my_car_back_btn:
			showProgress("车辆更新中...");
			if(null != CarListAdapter.vehicleInfos){
				for(int i = 0;i< CarListAdapter.vehicleInfos.size();i++){
					if(CarListAdapter.vehicleInfos.get(i).isModification()){
						updatedVehicleInfo = CarListAdapter.vehicleInfos.get(i);
						List<NameValuePair> params1 = new ArrayList<NameValuePair>();
						params1.add(new BasicNameValuePair("vehicleInfo.userId", userId + ""));
						params1.add(new BasicNameValuePair("vehicleInfo.id", CarListAdapter.vehicleInfos.get(i).getId()));
						if(null != CarListAdapter.vehicleInfos.get(i).getVehicleBrand()&&!"".equals(CarListAdapter.vehicleInfos.get(i).getVehicleBrand())){
							params1.add(new BasicNameValuePair("vehicleInfo.vehicleBrand", CarListAdapter.vehicleInfos.get(i).getVehicleBrand()));
						}
						if(null != CarListAdapter.vehicleInfos.get(i).getVehicleModels()&& !"".equals(CarListAdapter.vehicleInfos.get(i).getVehicleModels())){
							params1.add(new BasicNameValuePair("vehicleInfo.vehicleModels", CarListAdapter.vehicleInfos.get(i).getVehicleModels()));
						}
						if(null != CarListAdapter.vehicleInfos.get(i).getLicensePlateNumber()&&!"".equals(CarListAdapter.vehicleInfos.get(i).getLicensePlateNumber())){
							params1.add(new BasicNameValuePair("vehicleInfo.licensePlateNumber", CarListAdapter.vehicleInfos.get(i).getLicensePlateNumber()));
						}
						if(null != CarListAdapter.vehicleInfos.get(i).getInspectionExpireTime()&&!"".equals(CarListAdapter.vehicleInfos.get(i).getInspectionExpireTime())){
							params1.add(new BasicNameValuePair("vehicleInfo.inspectionExpireTime", CarListAdapter.vehicleInfos.get(i).getInspectionExpireTime().replaceAll("-", "-")));  //TODO mychange
						}
						if(null != CarListAdapter.vehicleInfos.get(i).getInsuranceEndTime()&&!"".equals(CarListAdapter.vehicleInfos.get(i).getInsuranceEndTime())){
							params1.add(new BasicNameValuePair("vehicleInfo.insuranceEndTime", CarListAdapter.vehicleInfos.get(i).getInsuranceEndTime().replaceAll("-", "-")));		//TODO mychange
						}
						new DataLoader(MyCarActivity.this).DisplayData(MainConstants.HOST_test
								+ HttpConfigAPI.UPDATE_VEHICLE, params1, handler1, "", false);
						
					}
				}
			}
			finishProgress();
			this.finish();
			break;
		case R.id.add_car_info_btn:
			intent.setClass(MyCarActivity.this, MyCarManagerActivity.class);
			startActivityForResult(intent, MainConstants.ADD_VEHICLE);
			break;
		default:
			break;
		}
	}

	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		my_car_back_btn = this.findViewById(R.id.my_car_back_btn);
		add_car_info_btn = this.findViewById(R.id.add_car_info_btn);
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		my_car_back_btn.setOnClickListener(this);
		add_car_info_btn.setOnClickListener(this);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub

	}
	protected String year;

	protected String month;

	protected String day;

	protected String endtiem;

	protected TextView car_annual_audit_deadline_tv;

	protected TextView car_insurance_deadline_tv;
	/**
	 * 时间选择器
	 */
	public DatePickerDialog.OnDateSetListener mSetDateListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear + "";
			month = monthOfYear +1+ "";
			day = dayOfMonth + "";

			MyCarActivity.calendar.set(Calendar.YEAR, myear);
			MyCarActivity.calendar.set(Calendar.MONTH, monthOfYear);
			MyCarActivity.calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			// week = int_to_str(calendar.get(Calendar.DAY_OF_WEEK));
			endtiem = year + "-" + month + "-" + day;
			if (CarListAdapter.ANNUAL_AUDIT_DEADLINE == CarListAdapter.flag) {
				/*car_annual_audit_deadline_tv = (TextView) lv_my_car.getChildAt(
						CarListAdapter.changeIndex).findViewById(
						R.id.car_annual_audit_deadline_tv);
				car_annual_audit_deadline_tv.setText(year + "-" + month + "-"+ day);*/
				VehicleInfo vehicleInfo3 = new VehicleInfo();
				vehicleInfo3.setId((CarListAdapter.vehicleInfos.get(CarListAdapter.changeIndex)).getId());
				vehicleInfo3.setInspectionExpireTime(endtiem);
				CarListAdapter adapter = (CarListAdapter)lv_my_car.getAdapter();
				adapter.updateDataItem(CarListAdapter.changeIndex, vehicleInfo3);
				MyCarActivity.this.removeDialog(position);
			} else {
				/*car_insurance_deadline_tv = (TextView) lv_my_car.getChildAt(
						position).findViewById(R.id.car_insurance_deadline_tv);
				car_insurance_deadline_tv.setText(year + "-" + month + "-"+ day);*/
				VehicleInfo vehicleInfo4 = new VehicleInfo();
				vehicleInfo4.setId((CarListAdapter.vehicleInfos.get(CarListAdapter.changeIndex)).getId());
				vehicleInfo4.setInsuranceEndTime(endtiem);
				CarListAdapter adapter = (CarListAdapter)lv_my_car.getAdapter();
				carListAdapter.updateDataItem(CarListAdapter.changeIndex, vehicleInfo4);
				MyCarActivity.this.removeDialog(position);
			}

		}
	
	};

	private int position;
	
	protected Dialog onCreateDialog(int id) {
		position = id;
		String date[] = null;
		switch (CarListAdapter.flag) {
		case CarListAdapter.ANNUAL_AUDIT_DEADLINE:
			System.out.println("ANNUAL_AUDIT_DEADLINE="+CarListAdapter.ANNUAL_AUDIT_DEADLINE+"    "+"flag"+CarListAdapter.flag);
			if(null != CarListAdapter.vehicleInfos.get(id).getInspectionExpireTime() && !CarListAdapter.vehicleInfos.get(id).getInspectionExpireTime().equals("") && !CarListAdapter.vehicleInfos.get(id).getInspectionExpireTime().equals("null")){
				date = CarListAdapter.vehicleInfos.get(id).getInspectionExpireTime().split("-");
				if (date.length == 3) {
					datepick = new DatePickerDialog(this, mSetDateListener,
							Integer.parseInt(date[0]), Integer.parseInt(date[1])-1,
							Integer.parseInt(date[2]));
				}			
			} else {
				calendar = Calendar.getInstance();
				datepick = new DatePickerDialog(this, mSetDateListener,
						calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH));
			}
			break;
		case CarListAdapter.CAR_INSURANCE_DEADLINE:
			System.out.println("ANNUAL_AUDIT_DEADLINE="+CarListAdapter.CAR_INSURANCE_DEADLINE+"    "+"flag = "+CarListAdapter.flag);
			if(null != CarListAdapter.vehicleInfos.get(id).getInsuranceEndTime() && !CarListAdapter.vehicleInfos.get(id).getInsuranceEndTime().equals("") && !CarListAdapter.vehicleInfos.get(id).getInsuranceEndTime().equals("null")){
				date = CarListAdapter.vehicleInfos.get(id).getInsuranceEndTime().split("-");
				if (date.length == 3) {
					datepick = new DatePickerDialog(this, mSetDateListener,
							Integer.parseInt(date[0]), Integer.parseInt(date[1])-1,
							Integer.parseInt(date[2]));
				}
			} else {
				calendar = Calendar.getInstance();
				datepick = new DatePickerDialog(this, mSetDateListener,
						calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH));
			}
			break;
		}
		
		return datepick;
	}

	public static Calendar calendar = Calendar.getInstance();

}
